package com.yh.blog.controller.admin;
import com.yh.blog.domain.Friend;
import com.yh.blog.service.FriendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 友情链接管理控制层
 */
@Controller
@RequestMapping("/admin")
public class FriendController {
    @Autowired
    private FriendService friendService;

//    友链列表
    @GetMapping("/friend")
    public String index(Model model, @RequestParam(value = "page",defaultValue = "1") Integer page){
        model.addAttribute("pager",this.friendService.list(page));
        return "admin/friends/friendlinks";
    }

//  跳转到新增友链页面
    @GetMapping("/friend/input")
    public String input(){
        return "admin/friends/friend-append";
    }
//    新增友链
    @PostMapping("/friend")
    public String append(Friend friend, RedirectAttributes attributes){
        if(this.friendService.append(friend)){
            attributes.addFlashAttribute("messages","新增成功");
        }else {
            attributes.addFlashAttribute("messages","新增失败");
        }
        return "redirect:/admin/friend";
    }

//    跳转到编辑友链页面
    @GetMapping("/friend/modify")
    public String editInput(@RequestParam("friendId") Integer friendId, Model model) {
        model.addAttribute("friend",this.friendService.detail(friendId));
        return "admin/friends/friend-modify";
    }
//    编辑友链
    @PostMapping("/friend/modify")
    public String editPost(Friend friend,RedirectAttributes attributes) {
        if(this.friendService.modify(friend)){
            attributes.addFlashAttribute("messages","修改成功");
        }else {
            attributes.addFlashAttribute("messages","修改失败");
        }
        return "redirect:/admin/friend";
    }


//  删除友链
    @RequestMapping("/friend/delete")
    public String delete(Integer friendId, RedirectAttributes attributes){
        this.friendService.Remove(friendId);
        attributes.addFlashAttribute("messages","删除成功");
        return "redirect:/admin/friend";
    }
}
